package com.demo.common.interceptor;

import com.demo.common.permission.PermissionCheck;
import com.demo.common.permission.PermissionService;
import com.demo.common.permission.login.RequestService;
import com.demo.common.utils.JsonUtil;
import com.demo.common.vo.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器，拦截PermissionCheck注解
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    private PermissionService permissionService;

    @Resource
    private RequestService requestService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception{
        //先找方法上的权限
        PermissionCheck permissionCheck = ((HandlerMethod) handler).getMethod()
                .getAnnotation(PermissionCheck.class);
        if (permissionCheck == null) {
            //没有的话找controller的
            Class<?> controller = ((HandlerMethod) handler).getBeanType();
            permissionCheck = controller.getAnnotation(PermissionCheck.class);
        }
        //找到了就校验
        if(permissionCheck!=null){
            Integer userId = requestService.getUserId();
            boolean check;
            if(permissionCheck.andModel()){
                check = permissionService.hasPermissionAll(userId,permissionCheck.value());
            }else{
                check = permissionService.hasPermissionRandom(userId,permissionCheck.value());
            }
            if(!check){
                Result error=Result.error("权限校验失败，请联系管理员开启权限后重试");
                response.getWriter().write(JsonUtil.object2Json(error));
                return false;
            }
        }
        //没有权限校验直接返回true
        return true;
    }
}
